package org.example.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NIOClient {

    private final int port = 5000;
    private final  String host = "127.0.0.1";
    private Selector selector;

    public static void main(String[] args) {
        NIOClient client = new NIOClient();
        client.connec();
        client.linsten();
    }



    private  void connec(){
        try {
            SocketChannel sc = SocketChannel.open();
            sc.configureBlocking(false);
            selector = Selector.open();
            sc.register(selector, SelectionKey.OP_CONNECT);
            sc.connect(new InetSocketAddress(host,port));
        } catch (IOException e) {
            e.printStackTrace();
        }




    }
    private void linsten(){
        try {
            while (true){
                int events = selector.select();
                if(events > 0 ){
                    Iterator<SelectionKey> tor = selector.selectedKeys().iterator();
                    while(tor.hasNext()){
                        SelectionKey selectionKey = tor.next();
                        tor.remove();
                        if(selectionKey.isConnectable()){
                            //连接事件
                            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                            if(socketChannel.isConnectionPending()){
                                socketChannel.finishConnect();
                            }
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            socketChannel.write(ByteBuffer.wrap(" client hello nio".getBytes()));
                        }else if(selectionKey.isReadable()){
                            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                            ByteBuffer buff = ByteBuffer.allocate(1024);
                            socketChannel.read(buff);
                            buff.flip();
                            System.out.println("收到服务器返回的数据:"+new String(buff.array()));
                        }

                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
